package com.whfc.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Base64;

/**
 * @ClasssName AliyunVcsUtil
 * @Description 阿里云智筑工具类
 * @Author hw
 * @Date 2020/8/13 11:09
 * @Version 1.0
 */
public class AliyunVcsUtil {

    private static Logger logger = LoggerFactory.getLogger(AliyunVcsUtil.class);

    /**
     * 云智筑APPID
     */
    private final static String APPID = "fengchaowulian";
    /**
     * 云智筑secret
     */
    private final static String SECRET = "rSFFLPPZBQKfIJTF9ZJwIKYuKmEhgnkL";

    private final static String VSCURL = "https://www.aliyunvcs.cn/construction_site/home.html?";

    public static String sign(String idsCorpId) throws UnsupportedEncodingException {
        logger.info("开始生成云智筑校验码,idsCorpId:{}", idsCorpId);
        StringBuffer paramStr = new StringBuffer();
        paramStr.append("appId=").append(URLEncoder.encode(APPID, "UTF-8")).append("&idsCorpId=").append(URLEncoder.encode(idsCorpId, "UTF-8")).append("&signatureMethod=")
                .append(URLEncoder.encode("HMAC-SHA1", "UTF-8")).append("&signatureVersion=1.0&timestamp=").append(System.currentTimeMillis());
        String signature = genHmacSha1(paramStr.toString(), SECRET);
        logger.info("生成校验码字符串：{},校验码：{}", paramStr.toString(), signature);
        paramStr.append("&signature=").append(URLEncoder.encode(signature, "UTF-8"));
        return VSCURL + paramStr.toString();
    }


    private static String genHmacSha1(String data, String key) {
        try {
            //根据给定的字节数组构造⼀个密钥,第⼆参数指定⼀个密钥算法的名称
            SecretKeySpec signinKey = new SecretKeySpec(key.getBytes(),
                    "HmacSHA1");
            //⽣成⼀个指定 Mac 算法 的 Mac 对象
            Mac mac = Mac.getInstance("HmacSHA1");
            //⽤给定密钥初始化 Mac 对象
            mac.init(signinKey);
            //完成 Mac 操作
            byte[] rawHmac = mac.doFinal(data.getBytes());
            return Base64.getEncoder().encodeToString(rawHmac);
        } catch (Exception e) {
            return null;
        }
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        System.out.println("请求连接：" + sign("2669386268797831300"));
//            System.out.println(genHmacSha1("POST&%2F&AccessKeyId%3DLTAI4GEHD93vzcnqunZJHdY3%26Action%3DCreateVideoComposeTask%26Format%3DJSON%26RegionId%3Dcn-hangzhou%26SignatureMethod%3DHMAC-SHA1%26SignatureNonce%3Dbf3bd4c0-dd46-11ea-8aae-c770dc0fe89f%26SignatureVersion%3D1.0%26Timestamp%3D2020-08-13T09%253A24%253A11Z%26Version%3D2020-05-15",SECRET));
    }


}
